﻿#region changelog
/*
 * 02/04/09 - wbw (Seagull Consulting): Original code
 * 02/16/09 - wbw: Added extra check for reserved XML characters in the overview that might cause problems down the line.
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;

namespace Durrant.Plugins.TvDB
{
    public class Episode
    {
        public string Nbr { get; set; }
        public string Id { get; set; }
        public string Name { get; set; }
        public string Season { get; set; }
        public string FirstAired { get; set; }
        public string Overview { get; set; }
        public string RecordDate { get; set; }

        public void parse(string episodeXML)
        {

            //Parse the id
            Id = getXMLTagValue(episodeXML, Constants.EPISODE_ID);

            //Parse the Name
            Name = removeXMLReservedCharacters(getXMLTagValue(episodeXML, Constants.EPISODE_NAME));

            //Parse FirstAired
            FirstAired = getXMLTagValue(episodeXML, Constants.EPISODE_FIRST_AIRED);

            //Parse the Overview
            Overview = removeXMLReservedCharacters(getXMLTagValue(episodeXML, Constants.EPISODE_OVERVIEW));
        }

        private string getXMLTagValue(string XML, string tag)
        {
            int beginLoc, endLoc = 0;
            beginLoc = XML.IndexOf(tag) + tag.Length + 1;
            if (beginLoc > 0)
            {
                endLoc = XML.IndexOf(tag, beginLoc) - 6;
                if (endLoc > 0)
                    return XML.Substring(beginLoc, endLoc - beginLoc);
                else
                    return string.Empty;
            }
            else
                return string.Empty;
        }

        private string removeXMLReservedCharacters(string xmlString)
        {
            StringBuilder returnString = new StringBuilder(xmlString);

            //Change XML reserved characters that may give us trouble later on
            returnString = returnString.Replace(Constants.XMLRESERVEDCHARAMPERSAND, Constants.XML_RESERVED_STRING_AMPERSAND);
            returnString = returnString.Replace(Constants.XML_RESERVERED_CHAR_PERCENT, Constants.XML_RESERVED_STRING_PERCENT);
            returnString = returnString.Replace(Constants.XML_RESERVED_CHAR_GT, string.Empty);
            returnString = returnString.Replace(Constants.XML_RESERVED_CHAR_LT, string.Empty);

            return returnString.ToString();
        }

    }
}
